<!DOCTYPE html>
<html lang="en">

<head>
    <title>js调用摄像头拍照上传图片</title>
    <meta charset="utf-8">
</head>

<body>
<!-- 摄像头画面框 -->
<video id="video" width="500px" height="500px" autoplay="autoplay"></video>
<button onclick="openMedia()">开启摄像头</button>

<!-- 拍照后展示的图片 -->
<canvas id="canvas" width="500px" height="500px"></canvas>
<button onclick="takePhoto()">拍照</button>

<!-- 测试将拍照得到的照片，赋给img标签的，src属性 -->
<img id="imgTag" src="" alt="imgTag">
<button onclick="closeMedia()">关闭摄像头</button>

<style>
    /* 设置摄像头显示框样式 */
    #video {
        border-radius: 200px;
        /* 翻转摄像头  */
        -moz-transform: scaleX(-1);
        -webkit-transform: scaleX(-1);
        -o-transform: scaleX(-1);
        transform: scaleX(-1);
    }
</style>

<!-- 测试用jQuery进行的远程测试 -->
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
    let mediaStreamTrack = null; // 视频对象(全局)
    let video;
    function openMedia() {
        let constraints = {
            video: { width: 500, height: 500 },
            audio: false
        };
        //获得video摄像头
        video = document.getElementById('video');
        let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then((mediaStream) => {
            // mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
            mediaStreamTrack = mediaStream.getVideoTracks()
            video.srcObject = mediaStream;
            video.play();
        });
    }

    // 拍照
    function takePhoto() {
        //获得Canvas对象
        let video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, 500, 500);
        ctx.translate(canvas.width, 0);
        ctx.scale(-1, 1);


        // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
        let img = document.getElementById('canvas').toDataURL();
        // 这里的img就是得到的图片
        console.log('img-----', img);
        document.getElementById('imgTag').src = img;
        //上传
        $.ajax({
            url: "/user/selectFace",
            type: "POST",
            data: {"file": img,"id":"1"},
            success: function (data) {
                console.log(data);
            },
            error: function () {
                console.log("服务端异常！");
            }
        });
    }

    // 关闭摄像头
    function closeMedia() {
        let stream = document.getElementById('video').srcObject;
        let tracks = stream.getTracks();

        tracks.forEach(function (track) {
            track.stop();
        });

        document.getElementById('video').srcObject = null;
    }
</script>
</body>